package com.ncloud.system.controller;

import com.alibaba.fastjson.JSON;
import com.ncloud.common.body.Result;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.ResultUtil;
import com.ncloud.system.business.DepartBusi;
import com.ncloud.system.entity.Depart;
import com.ncloud.system.entity.Role;
import com.ncloud.system.service.DepartService;
import com.ncloud.system.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by shiqiang on 2017/7/28.
 */
@Api(value = "自动化运维部门管理", description = "部门管理", tags = "部门管理",
        basePath="/",consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/sys")
public class DepartController {
    private final static Logger logger = LoggerFactory.getLogger(DepartController.class);
    @Autowired
    private DepartBusi departBusi;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DepartService departService;
    /*生成菜单*/
    @ApiOperation(value="create depart", notes="部门创建")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
            @ApiImplicitParam(name = "部门", value = "部门信息", required = true, dataType = "Depart" )
    })
    @PostMapping(value = "/depart")
    public Result<Object> saveDepart(HttpServletRequest request, @RequestBody Depart json) throws Exception {
        Object userID = request.getAttribute("userID");
        if(StringUtils.isEmpty(userID)){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"用户id不存在！");
        }else{
            json.setCreateUser(Long.parseLong(userID.toString()));
        }
        logger.info("depart info={%s}"+ JSON.toJSONString(json));
        departBusi.addDepart(json);
        return ResultUtil.success();
    }

    @ApiOperation(value="update depart", notes="部门修改")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String"),
            @ApiImplicitParam(name = "部门", value = "部门信息", required = true, dataType = "Depart" )
    })
    @PutMapping(value = "/depart")
    public Result<Object> updateDepart(HttpServletRequest request, @RequestBody Depart json) throws Exception {
        Object userID = request.getAttribute("userID");
        if(StringUtils.isEmpty(userID)){
            throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"用户id不存在！");
        }else{
            json.setUpdateUser(Long.parseLong(userID.toString()));
        }
        logger.info("depart info={%s}"+ JSON.toJSONString(json));
        departBusi.modifyDepart(json);
        return ResultUtil.success();
    }
    @ApiOperation(value="deleteDepart", notes="删除部门，根据部门id，删除当前部门和部门权限")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String")
    })
    @DeleteMapping(value = "/depart/{companyId}/{departId}")
    public Result<Object> deleteDepart(@PathVariable("companyId") Long companyId,@PathVariable("departId") Long departId) throws Exception {
        departBusi.deleteDepart(companyId,departId);
        return ResultUtil.success();
    }
    /*根据公司查询对应的分组信息*/
    @ApiOperation(value="getDepart", notes="获取部门组，根据用户权限获取")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String")
    })
    @GetMapping(value = "/depart/allDeparts")
    public Result<List<Depart>> getDepart(HttpServletRequest request) throws Exception {
        Object userID = request.getAttribute("userID");
        String roleId = request.getParameter("roleId");
        if(StringUtils.isEmpty(userID)){
            throw new UserException(2001,"用户ID不存在！");
        }else{
            List<Depart> departs = departBusi.getDepartInfo(Long.parseLong(userID.toString()));
            return ResultUtil.success(departs);
        }
    }

    /*根据部门id获取详细信息*/
    @ApiOperation(value="getDepart", notes="获取部门组，根据部门id获取其详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String")
    })
    @GetMapping(value = "/depart/detail/{departId}")
    public Result<Depart> getRolesById(HttpServletRequest request,@PathVariable("departId") Long departId) throws Exception {
        Depart depart = departBusi.getDepartDetail(departId);
        return ResultUtil.success(depart);
    }


    /*根据公司查询其下的角色*/
    @ApiOperation(value="公司下角色获取", notes="获取公司下的角色信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String")
    })
    @GetMapping(value = "/depart/role/{companyId}")
    public Result<List<Role>> getRolesByCompanyId(HttpServletRequest request,@PathVariable("companyId") Long companyId) throws Exception {
        List<Role> roles = roleService.getRolesByCompanyId(companyId);
        return ResultUtil.success(roles);
    }

    /*获取分组下的账号数departService.getDepartAccountNum(depart.getDepartId())*/
    @ApiOperation(value="获取分组下的账号数", notes="获取分组下的账号数")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String")
    })
    @GetMapping(value = "/depart/accountNum/{departId}")
    public Result<List<Role>> getDepartAccountNum(HttpServletRequest request,@PathVariable("departId") Long departId) throws Exception {
        int num  = departService.getDepartAccountNum(departId);
        return ResultUtil.success(num);
    }


    /*根据公司查询其下的分组*/
    @ApiOperation(value="获取公司下的分组信息", notes="获取公司下的分组信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",name = "X-CSRF-TOKEN" ,required = true,dataType = "String")
    })
    @GetMapping(value = "/depart/departInfo/{companyId}")
    public Result<List<Depart>> getDepartInfoByCompanyId(HttpServletRequest request,@PathVariable("companyId") Long companyId) throws Exception {
        return ResultUtil.success(departService.getDepartsByCompanyId(companyId));
    }
}
